package com.gensdai.leliang.activity;

import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AlertDialog;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextPaint;
import android.text.TextUtils;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.text.style.URLSpan;
import android.text.util.Linkify;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import com.facebook.drawee.view.SimpleDraweeView;
import com.gensdai.leliang.R;
import com.gensdai.leliang.base.BaseActivity;
import com.gensdai.leliang.common.bean.LogisticsInfoBean;
import com.gensdai.leliang.entity.parseBean.BaseParse;
import com.gensdai.leliang.remoteInterface.RetrofitFactory;
import com.gensdai.leliang.remoteInterface.URLConfig;
import com.gensdai.leliang.retrofitUtils.BaseObserver;
import com.gensdai.leliang.retrofitUtils.ModelFilteredFactory;
import com.gensdai.leliang.view.Toaster;
import com.github.qing.stepviewlib.StepView;
import com.trello.rxlifecycle2.android.ActivityEvent;

import java.util.HashMap;
import java.util.Map;
import java.util.regex.Pattern;

import butterknife.BindView;
import butterknife.ButterKnife;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;

/*物流信息
 * Created by zsxx on 2017/6/27.
 */

public class LogisticsInfoActivity extends BaseActivity {
    @BindView(R.id.stepView)
    StepView stepView;
    @BindView(R.id.logisticproductImg)
    SimpleDraweeView logisticproductImg;
    @BindView(R.id.logisticNo)
    TextView logisticNo;
    @BindView(R.id.logisticname)
    TextView logisticname;
    @BindView(R.id.logisticSendTime)
    TextView logisticSendTime;


    @Override
    protected String getTitleStr() {
        return "物流信息";
    }

    @Override
    protected boolean isShowBackButton() {
        return true;
    }

    @Override
    protected boolean isCustomTitle() {
        return false;
    }

    @Override
    protected int getLayoutResource() {
        return R.layout.layout_logistics_list;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ButterKnife.bind(this);
        String order = getIntent().getStringExtra("orderid");


        getData(order);
    }

    private void getData(String order) {

        Map<String, String> params = new HashMap<>();
        params.put("orderId", order);

        ModelFilteredFactory.compose(RetrofitFactory.getInstance().API().getLogisticsInfo(params))
                .compose(this.<BaseParse<LogisticsInfoBean>>bindUntilEvent(ActivityEvent.DESTROY)) //跟生命周期绑定一起
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(@NonNull Disposable disposable) throws Exception {
                        Log.d("accept", "accept");
                    }
                })
                .subscribe(new BaseObserver<LogisticsInfoBean>(this) {
                    @Override
                    public void onHandleSuccess(LogisticsInfoBean t) {
                        if (t != null)
                            initView(t);
                    }

                    @Override
                    public void onHandleError(int code, String message) {
                        Toaster.showOneToast(code + " : " + message);
                    }
                });
    }

    private void initView(LogisticsInfoBean info) {

        logisticname.setText(info.getPerson());
        logisticNo.setText(info.getOrderNo());
        logisticSendTime.setText(info.getPayTime());
        if(!TextUtils.isEmpty(info.getLogoPic())){
            Uri uri = Uri.parse(URLConfig.BASEDOMAIN+info.getLogoPic());
            logisticproductImg.setImageURI(uri);
        }

//        LogisticsInfoBean.LogisticsListBean b = new LogisticsInfoBean.LogisticsListBean();
//        b.setOpeRemark("您的订单正在配送途中，请您准备签收（配送员王五，电话：15465233321感谢您的耐心等待");
//        b.setOpeTime("2017-04-18 13：04");
//
//        List<LogisticsInfoBean.LogisticsListBean> list =  info.getLogisticsList();
//        list.add(b);
//        list.addAll(info.getLogisticsList());
//        list.addAll(info.getLogisticsList());


        // 指定数据集合
        stepView.setDatas(info.getLogisticsList());
// 设置view的绑定监听
        stepView.setBindViewListener(new StepView.BindViewListener() {
            @Override
            public void onBindView(TextView itemMsg, TextView itemDate, Object data) {
                LogisticsInfoBean.LogisticsListBean sid = (LogisticsInfoBean.LogisticsListBean) data;
                itemMsg.setText(formatPhoneNumber(itemMsg,sid.getOpeRemark()));
                itemDate.setText(sid.getOpeTime());
            }
        });


    }


    /*手机号码格式化处理*/
    private static final String PATTERN_PHONE = "((13[0-9])|(14[5|7])|(15([0-3]|[5-9]))|(18[0,5-9]))\\d{8}";
    private static final String SCHEME_TEL = "tel:";
    private SpannableStringBuilder formatPhoneNumber(TextView textView, String source) {
        // 若要部分 SpannableString 可点击，需要如下设置
        textView.setMovementMethod(LinkMovementMethod.getInstance());
        // 将要格式化的 String 构建成一个 SpannableStringBuilder
        SpannableStringBuilder value = new SpannableStringBuilder(source);

        // 使用正则表达式匹配电话
        Linkify.addLinks(value, Pattern.compile(PATTERN_PHONE), SCHEME_TEL);

        // 获取上面到所有 addLinks 后的匹配部分(这里一个匹配项被封装成了一个 URLSpan 对象)
        URLSpan[] urlSpans = value.getSpans(0, value.length(), URLSpan.class);
        for (final URLSpan urlSpan : urlSpans) {
            if (urlSpan.getURL().startsWith(SCHEME_TEL)) {
                int start = value.getSpanStart(urlSpan);
                int end = value.getSpanEnd(urlSpan);
                value.removeSpan(urlSpan);
                value.setSpan(new ClickableSpan() {
                    @Override
                    public void onClick(View widget) {
                        String phone = urlSpan.getURL().replace(SCHEME_TEL, "");
                        AlertDialog.Builder builder = new AlertDialog.Builder(LogisticsInfoActivity.this);
                        builder.setMessage("是否拨打电话：" + phone);
                        builder.setNegativeButton("取消", null);
                        builder.setPositiveButton("确定", null);
                        builder.create().show();
                    }

                    @Override
                    public void updateDrawState(TextPaint ds) {
                        super.updateDrawState(ds);
                        ds.setColor(Color.parseColor("#3f8de2"));
                        ds.setUnderlineText(true);
                    }
                }, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            }
        }
        return value;
    }
}
